import { getAlbums, createAlbum } from '../../api/album'
import { DOMAIN_NAME } from '../../utils/request'
import { isEmpty } from '../../utils/validator'

var toptip // 保存toptip组件的引用
Page({
  data: {
    album_name: '',
    modalName: '',
    DOMAIN_NAME: DOMAIN_NAME,
    query: {
      _paginator: 'none',
    },
    first_albums: null,
    albums: [],
    // result: [],
    loadMoreStatus: 'hidding'
  },
  onLoad(e) {
    wx.showLoading({ title: '加载中', mask: true })
    this._fetchData(this.data.query).then(res => {
      if (res.length > 0) {
        this.setData({
          first_albums: res[0]  // 循环时，排除了第一个
        })
      }
    }).finally(() => wx.hideLoading())
  },


  onReady: function () {
    toptip = this.selectComponent('#toptip')
  },

  albumNameBlur(e) {
    this.setData({
      album_name: e.detail.value
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  createAlbumTap() {
    let { album_name } = this.data
    if (isEmpty(album_name)) {
      return toptip.show('相册名称不能为空')
    }
    createAlbum({ 'name': this.data.album_name }).then(res => {
      toptip.show('创建成功', { type: 'success' })
      let albums = this.data.albums
      // console.log(albums.length, res.data)
      if (albums.length == 0) {
        this.setData({
          first_albums: res.data,
          albums: [res.data]
        })
      } else {
        albums.splice(1, 0, res.data)  // 在第二个位置插入
        this.setData({
          albums: albums
        })
      }
      // cons
      this.setData({
        modalName: null,
        album_name: ''
      })
      return

    }).catch((res) => {
      return toptip.show(res.data.msg.name[0])
    })
  },
  hideModal(e) {
    if (this.data.modalName == 'album') {
      this.setData({
        album_name: ''
      })
    }
    this.setData({
      modalName: null
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // let { query, result } = this.data
    // if (result.has_next) {
    //   query['page'] = result.next
    //   this.setData({ loadMoreStatus: 'loading' })
    //   this._fetchData(query).then(res => {
    //     console.log(res)
    //     this.setData({ loadMoreStatus: 'nomore' })
    //   }).catch(()=>this.setData({ loadMoreStatus: 'hidding' }))
    // }
  },
  _fetchData: function (query) {
    return getAlbums(query).then(res => {
      this.setData({
        // result: res.data,  // 记录分页等查询信息
        albums: res.data,
      })
      return res.data
    }).catch(() => {
      return []
    })
  }
})